<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="http://cdn.bootcss.com/jqueryui/1.11.4/jquery-ui.css" />
<script type="text/javascript"  src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script>
$( document ).ready(function() {
    // Get Layout Name from GET
    var vars = {};
    window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    if (typeof vars['layoutName'] !== 'undefined'){
        loadFile(vars['layoutName']);
    }

    var headers = $('#accordion').find(".accordion-header");
    // add the accordion functionality
    headers.click(function() {
        var panel = $(this).next();
        var isOpen = panel.is(':visible');
        // open or close as necessary
        panel[isOpen? 'slideUp': 'slideDown']()
            // trigger the correct custom event
            .trigger(isOpen? 'hide': 'show');
        // stop the link from causing a pagescroll
        return false;
    });
    $(".ui-icon-circle-close").click(function(){
        if (confirm("Close?")) $(this).closest(".accordion-session").remove();
    });
    //Add Category
    $('#session_add').click(function(){
        var accordion_header = $('<h3 class="accordion-header ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-corner-all">' +
                        '<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span><span class="section-description">新增類別</span>'+
                        '<span class="ui-icon ui-icon-circle-close" style="float:right" onclick="if (confirm(\'Close?\')) $(this).closest(\'.accordion-session\').remove();"></span><span class="ui-icon ui-icon-pencil" style="float:right"></span>' +
                      '</h3>').click(function(){
                            var panel = $(this).next();
                            var isOpen = panel.is(':visible');
                            // open or close as necessary
                            panel[isOpen? 'slideUp': 'slideDown']()
                                // trigger the correct custom event
                                .trigger(isOpen? 'hide': 'show');
                            // stop the link from causing a pageScroll
                            return false;                                      
                      });
        accordion_header.find(".ui-icon-pencil").click(function(){
            sessionDialog($(this).closest(".accordion-session"));
        });
        var accordion_session = $("<div class='accordion-session'></div>").append(accordion_header).append('<div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"></div>');
        accordion_session.appendTo($("#accordion"));
        attributeDroppable(accordion_session.find('.ui-accordion-content'));
    });
    // Have each session be able to extended v v
    $(".portlet")
      .addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
      .find( ".portlet-header" )
        .addClass( "ui-widget-header ui-corner-all" );      
    $(".portlet").draggable({ opacity: 0.7, helper: "clone" });
    attributeDroppable($(".ui-accordion-content"));
    $('#save').click(function(){save();});
});
// Analyze the data user input and output as xml file
function save(){                         
    var $root = $("<root />");
    //Cetagory Loop
    $.each($(".accordion-session"), function(i, session){
        var $layout_category = $("<layout_category />");
        var $category_name = $("<category_name />").text('section' + i);
        var $category_description = $("<category_description />").text($(this).find('.section-description').text());
        $layout_category.append($category_name).append($category_description);
        var $record = $("<record />");       
        var record_num = 0;
        var textarea_num = 0;
        // Attribute Loop
        $.each($(this).find('.portlet-drop'), function(j, portlet){
            record_num++;
            if (record_num > 20){
                record_num = 1;
                $record.appendTo($layout_category);
                $record = $("<record />");
                textarea_num = 0;
            }
            var field_type = $(portlet).data('field_type');
            if (field_type === 'limit_num'){
                if (record_num === 20){
                    record_num = 1;
                    $record.appendTo($layout_category);
                     $record = $("<record />");
                     textarea_num = 0;
                }
                var $field = recordSave(record_num, 'number', $(portlet).find('.field-description').text(), $(portlet).find('.field-default').text());
                record_num++;
                var $display_type = $("<display_type />").text('bar');
                var $extra_field = $("<extra_field />").text('field' + record_num);
                var $display = $("<display />").text('field' + (record_num-1) + '/field' + record_num);
                $("<custom_display />").append($display_type).append($extra_field).append($display).appendTo($field);
                $record.append($field);                            
                $field = recordSave(record_num, 'number', $(portlet).find('.field-description').text() + "MAX", $(portlet).find('.field-max').text());
                $field.append("<field_skip>true</field_skip>");
                $record.append($field);                            
            }
            else if (field_type === 'custom'){
                if (record_num === 20){
                    record_num = 1;
                    $record.appendTo($layout_category);
                     $record = $("<record />");
                     textarea_num = 0;
                }
                var $field = recordSave(record_num, 'text', '技能', $(portlet).find('.field-description').text());
                record_num++;
                var $display_type = $("<display_type />").text('bar');
                var $extra_field = $("<extra_field />").text('field' + record_num);
                var $display = $("<display />").text('(field' + (record_num-1) + ')field' + record_num);
                $("<custom_display />").append($display_type).append($extra_field).append($display).appendTo($field);                            
                $record.append($field);
                $field = recordSave(record_num, 'text', '技能V', $(portlet).find('.field-default').text());
                $field.append("<field_skip>true</field_skip>");
                $record.append($field);                                      
            }
            else if (field_type === 'textarea'){
                textarea_num++;
                if (textarea_num > 3){
                    record_num = 1;
                    $record.appendTo($layout_category);
                    $record = $("<record />");
                    textarea_num = 1;
                }
                var $field = recordSave(textarea_num, field_type,  $(portlet).find('.field-description').text(), $(portlet).find('.field-default').text());
                if ($record.find("field").eq(textarea_num -1).find('display').length > 0){
                    var field_num = $record.find("field").eq(textarea_num -1).find('field_column').text();
                    var display = $record.find("field").eq(textarea_num -1).find('display').text().replace(field_num, 'Field' + record_num);
                    $record.find("field").eq(textarea_num -1).find('display').text(display);
                }
                $record.find("field").eq(textarea_num -1).find('field_column').text('Field' + record_num);
                $record.find("field").eq(textarea_num -1).find('field_name').text('Field' + record_num);
                
                $record.append($field);                            
            }
            else{                            
                var $field = recordSave(record_num, field_type,  $(portlet).find('.field-description').text(), $(portlet).find('.field-default').text());
                $record.append($field);
            }
        });
        $record.appendTo($layout_category);
        $layout_category.appendTo($root);
    });
    download($root.html());
}

//Generate Attribute XML tag
function recordSave(record_num, field_type, field_description, $field_default){
    var $field_column = $("<field_column />").text('field' + record_num);
    var $field_name = $("<field_name />").text('field' + record_num);
    var $field_description = $("<field_description />").text(field_description).attr('lang', 'zh');
    var $field_type = $("<field_type />").text(field_type);
    var $field_default = $("<field_default />").text($field_default);
    var $field =  $("<field />").append($field_column).append($field_name).append($field_description).append($field_type).append($field_default);                  
    return $field;
}
function download(X)
{               
    var dataUrl='data:application/download,' + encodeURIComponent(
            '<\?xml version="1.0" encoding="UTF-8"?><root>'
            + X + "</root>"
            );
    $("<a download='save.xml' href='"+dataUrl+"'></a>")[0].click();
}
function editDialog($session){
    var origValue = $session.find('.section-description').text().replace(/'/g, "\\'");;
    $("<div><label for='name'>類別名稱:</label><input class='thisName'  type='text' value='" + origValue +"'/></div>").prop('title', "類別名稱").dialog({
        modal: true,
        width:450,
        buttons: {
            '更新': function(){
                $session.find('.section-description').text($(this).find(".thisName").val());
                $( this ).dialog( "destroy" );
            },
            Cancel: function(){
                $( this ).dialog( "close" );
                $( this ).dialog( "destroy" );
            }
        }
    });
}

function loadFile(layoutName)
{
    $.ajax({
            dataType: "json",
            type: "POST",
            url: "layout_maker_ajax.php",
            data: {
                action: "load_file",
                layoutName: layoutName
            },
            error: function(xhr, textStatus, error){
                console.log(xhr.statusText);
                console.log(textStatus);
                console.log(error);
            }
        })
        .done(function( msg ) {
            $(".accordion-session").remove();

            $.each(msg.data, function(index, fields){
                $("#session_add").click();
                //alert(index);
                var $session = $(".accordion-session:last-of-type .ui-accordion-content");
                $session.closest(".accordion-session").find(".section-description").text(msg.categories[index].description);

                $.each(fields, function(index2, field){
                    var span = attributeElement();
                    var remove = $('<span class="ui-icon ui-icon-circle-close" style="float:right;cursor:pointer"></span>').click(function(){
                        if (confirm('確認刪除?')){
                            $(this).closest('.portlet-drop').remove();
                        }
                    });
                    //console.log(field);
                    var html = "";
                    if (typeof  field.field_default === 'object' || typeof  field.field_default === 'undefined')field.field_default ="";
                    if (typeof  field.custom_display !== 'undefined'){
                        if (typeof  field.extra_field.field_default === 'object'){field.extra_field.field_default ="";}
                        if (field.custom_display.display.indexOf("/") >= 0){
                            field.field_type = "limit_num";
                            html = "<span class='field-description'>" + field.field_description + "</span> <span class='field-default field-hidden'>" +field.field_default +"</span>" + " <span class='field-max field-hidden'>" + field.extra_field.field_default+ "</span>";
                        }
                        else {
                            field.field_type = "custom";
                            html = "<span class='field-description'>" + field.field_description + "</span> <span class='field-default field-hidden'>" +field.extra_field.field_default +"</span>";
                        }
                    }
                    else{
                        html = "<span class='field-description'>" + field.field_description + "</span> <span class='field-default field-hidden'>" +field.field_default +"</span>";
                    }
                    var portlet = $(".portlet[data-field_type='"+ field.field_type+ "']").clone()
                        .removeClass('portlet').addClass('portlet-drop').css('opacity', "1.0").css('position','static')
                        .find('.portlet-header').append(remove).append(span).closest('.portlet-drop')
                        .appendTo($session);
                    portlet.find('.portlet-content').html(html);
                });
            });
        });
}
function attributeDialog($session, dialog_content){
    $("<div>"+dialog_content+"</div>").prop('title',$session.find('.field-type').text()).dialog({
        modal: true,
        width:450,
        buttons: {
            '更新': function(){
                $( this ).dialog( "close" );
                $session.find('.field-description').text($( this ).find('.field-description').val());
                $session.find('.field-default').text($( this ).find('.field-default').val());
                if($session.data('field_type') === 'limit_num'){
                    $session.find('.field-max').text($( this ).find('.field-max').val());
                }
                $( this ).dialog( "destroy" );
            },
            Cancel: function(){
                $( this ).dialog( "close" );
                $( this ).dialog( "destroy" );
            }
        },
        open: function( event, ui ){
            $(this).find('.field-description').val($session.find('.field-description').text());
            $(this).find('.field-default').val($session.find('.field-default').text());
            if ($session.data('field_type') === 'limit_num'){
                $(this).find('.field-max').val($session.find('.field-max').text());
            }
        }
    });
}

function sessionDialog($session){
    $("<div><label class='col-md-4'>類別名稱</label><input type='text' class='col-md-8'/></div>").prop('title', '類別名稱修正').dialog({
        modal: true,
        width:450,
        buttons: {
            '更新': function(){
                $session.find(".section-description").text($(this).find('input').val());
                $( this ).dialog( "close" );
            },
            Cancel: function(){
                $( this ).dialog( "close" );
                $( this ).dialog( "destroy" );
            }
        },
        open: function( event, ui ){
            $(this).find('input').val($session.find(".section-description").text());
        }
    });
}
function attributeElement(){
    var span = $('<span class="ui-icon ui-icon-pencil" style="float:right;cursor:pointer"></span>').click(function(){
        var $session = $(this).closest('.portlet-drop');
        var dialog_content = "";
        if ($session.data('field_type') === 'number'){
            dialog_content = "<span class='col-md-12'><label class='col-md-4'>名稱:</label><input type='text' class='field-description col-md-8' value=''></span>"+
                "<span class='col-md-12'><label class='col-md-4'>預設數值:</label><input type='number' class='field-default col-md-8' value='0'></span>";

        }else if ($session.data('field_type') === 'text' || $session.data('field_type') === 'textarea'){
            dialog_content = "<span class='col-md-12'><label class='col-md-4'>名稱:</label><input type='text' class='field-description col-md-8' value=''></span>"+
                "<span class='col-md-12'><label class='col-md-4'>預設字元:</label><input type='text' class='field-default col-md-8' value=''></span>";
        }else if ($session.data('field_type') === 'limit_num'){
            dialog_content = "<span class='col-md-12'><label class='col-md-4'>名稱:</label><input type='text' class='field-description col-md-8' value=''></span>"+
                "<span class='col-md-12'><label class='col-md-4'>預設數值:</label><input type='text' class='field-default col-md-8' value='0'></span>"+
                "<span class='col-md-12'><label class='col-md-4'>預設上限:</label><input type='text' class='field-max col-md-8' value=''></span>";
        }else if ($session.data('field_type') === 'custom'){
            dialog_content = "<span class='col-md-12'><label class='col-md-4'>預設名稱:</label><input type='text' class='field-description col-md-8' value=''></span>"+
                "<span class='col-md-12'><label class='col-md-4'>預設數值:</label><input type='text' class='field-default col-md-8' value=''></span>";
        }
        attributeDialog($session, dialog_content);

    });
    return span;
}
function attributeDroppable($dropElement){
    $dropElement.droppable({
        accept:'.portlet',
        drop: function(event,ui){
            var span = attributeElement();

            var remove = $('<span class="ui-icon ui-icon-circle-close" style="float:right;cursor:pointer"></span>').click(function(){
                if (confirm('確認刪除?')){
                    $(this).closest('.portlet-drop').remove();
                }
            });
            $(ui.helper).clone(true).removeClass('portlet').addClass('portlet-drop').css('opacity', "1.0").css('position','static')
                .find('.portlet-header').append(remove).append(span).closest('.portlet-drop')
                .appendTo(this);
        }
    });
    $dropElement.sortable();
    $dropElement.disableSelection();
}
</script>
<style>
    #left{
        float:left;
        width:150px;
    }
    #right{
        float:left;
        width:calc(100% - 150px);
    }
    .field-type{
        text-align: center;
        font-size: 18px;
        height: 60px;
    }
    .portlet, .portlet-drop {
      margin: 0 1em 1em 0;
      padding: 0.3em;
    }
    .portlet-drop {
        width:130px;
        display: inline-table;
    }
    .portlet-header {
      padding: 0.2em 0.3em;
      margin-bottom: 0.5em;
      text-align: center;
      position: relative;
      font-size: 12px;
    }         
    .portlet-content {
      padding: 0.4em;
    }  
</style>
</head>
<body>
<button id='session_add'>新增一列別</button><button id='save'>儲存</button><br />
<div id="left">
    <div class="portlet" data-field_type='number'>
      <div class="portlet-header"><span class="field-type">數值</span></div>
      <div class="portlet-content">
          <span class="field-description"></span>
          <span class="field-default field-hidden"></span>
      </div>
    </div>
    <div class="portlet" data-field_type='text'>
      <div class="portlet-header"><span class="field-type">文字</span></div>
      <div class="portlet-content">
          <span class="field-description"></span>
          <span class="field-default field-hidden"></span>
      </div>
    </div>
    <div class="portlet" data-field_type='textarea'>
      <div class="portlet-header"><span class="field-type">段落</span></div>
      <div class="portlet-content">
          <span class="field-description"></span>
          <span class="field-default field-hidden"></span>
      </div>
    </div>
    <div class="portlet" data-field_type='limit_num'>
      <div class="portlet-header"><span class="field-type">有上限數</span></div>
      <div class="portlet-content">
          <span class="field-description"></span>
          <span class="field-default field-hidden"></span>
          <span class="field-max field-hidden"></span>
      </div>
    </div>     
    <div class="portlet" data-field_type='custom'>
      <div class="portlet-header"><span class="field-type">自訂</span></div>
      <div class="portlet-content">
          <span class="field-description"></span>
          <span class="field-default field-hidden"></span>
      </div>
    </div>                  
</div>
<div id="right">
    <div id="accordion" class="ui-accordion ui-widget ui-helper-reset">
        <div class="accordion-session" >
            <h3 class="accordion-header ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-corner-all">
                <span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span>
                <span class="section-description">Section 1</span>
                <span class="ui-icon ui-icon-circle-close" style="float:right"></span>
                <span class="ui-icon ui-icon-pencil" style="float:right" onclick="editDialog($(this).closest('.accordion-session'))"></span>
            </h3>
            <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" style='height:200px;'>
            </div>
        </div>
        <div class="accordion-session">
            <h3 class="accordion-header ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-corner-all">
                <span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span>
                <span class="section-description">Section 2</span>
                <span class="ui-icon ui-icon-circle-close" style="float:right"></span>
                <span class="ui-icon ui-icon-pencil" style="float:right" onclick="editDialog($(this).closest('.accordion-session'))"></span>
            </h3>
            <div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom">
            </div>
        </div>                
    </div>
</div>
</body>
</html>